<?php
/*\
 *	
 *	
 *	
 *	
\*/

function dmodel_query($sql,$return="resultset") {
	global $dmdb;	
	
	#$dmdb->autotest();
		
	//$at = oh_debug_at("dmodel_query");
	//oh_debug_file_append("dmodel.log","$sql\n$at\n\n");
	//oh_dump($sql);
	
	if (false) {
	} else if ($return=="lastid") {
		$dmdb->query($sql);	
		return $dmdb->insert_id;
	} else if ($return=="record") {
		return $dmdb->get_row($sql);
	} else if ($return=="resultset") {
		$resultset = $dmdb->get_results($sql);
		$index = 0;
		if (count($resultset)>0) {
			foreach($resultset as $record) {
				$record->info = new stdClass();
				$record->info->index 	= $index;
				$record->info->odd 		= $index%2;
				$index++;
			}
		}
		return $resultset;
	} else {	
		return $dmdb->get_results($sql);	
	}
}

function dmodel_get_row($sql) {
	global $dmdb;
	return $dmdb->get_row($sql);
}

function dmodel_sql_insert($a) {
	$o = new stdClass();
	$f = array();
	$v = array();				
	if (is_object($a)) {
		//$c = $this->get_class($a->form);
		foreach($a as $key=>$value) {
			$f[] = $key;
			$v[] = "'".$value."'";	
		}		
		$o->fields = implode(",",$f);
		$o->values = implode(",",$v);	
	} else {
		$o->fields = "";
		$o->values = "";		
	}
	return $o;
}

function dmodel_install($prefix="oh_") {			
	$p = dmodel_get_prefix($prefix);
	
	$sql = "SELECT meta_value FROM {$p}meta WHERE meta_key='oh.module.model.installed'";
	if (!dmodel_get_row($sql)) {
		//oh_message("Model intalling...");
		//$prefix = $this->get_prefix($prefix);
		
		$s = file_get_contents(dirname(__FILE__)."/model.sql");
		$s = explode("--[QUERY]--",$s);
		
		foreach($s as $q) {
			$q = str_replace("__PREFIX__",$p,$q);
			dmodel_query($q);						
		}
	}
}

function dmodel_connect($user,$pass,$name,$host) {
	global $dmdb;
	$dmdb->now_connect($user,$pass,$name,$host);
	dmodel_install();
}

function dmodel_set_datasource($datasource) {
	global $dmdb;
	$dmdb = oh($datasource);
}
